package main

import (
	"fmt"
	"net"
)

type UDPSenderConfig struct {
	IP   string `json:"ip,omitempty"`
	Port int    `json:"port,omitempty"`
}

type UDPSender struct {
	config UDPSenderConfig
	conn   *net.UDPConn
}

func NewUDPSender(config UDPSenderConfig) (*UDPSender, error) {
	sip := net.ParseIP(config.IP)
	srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
	dstAddr := &net.UDPAddr{IP: sip, Port: config.Port}

	conn, err := net.DialUDP("udp", srcAddr, dstAddr)
	if err != nil {
		return nil, err
	}
	s := UDPSender{
		config: config,
		conn:   conn,
	}
	return &s, nil
}

func (u *UDPSender) Send(data []byte) error {
	num, err := u.conn.Write(data)
	if err != nil {
		return err
	}
	if num != len(data) {
		return fmt.Errorf("truncated write: %s", num)
	}
	return nil
}
